/**
 * 
 */
package net.empego.db;

import java.util.logging.Logger;

import javax.ejb.Asynchronous;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 * @author Thomas
 * 
 */
@Stateful
public class SiteMapDAOBean implements SiteMapDAO {

	// @Inject
	private final Logger log = Logger.getLogger(SiteMapDAOBean.class.getName());

	@PersistenceContext(unitName = "primary-jta")
	private EntityManager em;

	@Override
	@Asynchronous
	public void createSiteMap(final int hierachy, final int length, final String prefix, final String rootlabel) {
		// em.joinTransaction();
		if (findSiteMap(rootlabel) != null) {
			return;
		}
		final SiteMapEntryDO root = new SiteMapEntryDO(rootlabel, null);
		createSiteMapChildren(root, hierachy, 0, length, prefix);
		log.info("save sitemap...");
		em.persist(root);
		log.info("save sitemap done");
	}

	private void createSiteMapChildren(final SiteMapEntryDO siteMapEntry, final int hierachy, final int level, final int length,
			final String prefix) {

		if (level >= hierachy) {
			return;
		}

		final int currentLevel = level + 1;
		for (int i = 0; i < length; i++) {
			final SiteMapEntryDO entry = new SiteMapEntryDO(prefix + "_" + level + "_" + i, siteMapEntry);
			log.info("created: " + entry);
			createSiteMapChildren(entry, hierachy, currentLevel, length, prefix);
		}
	}

	@Override
	public SiteMapEntryDO findSiteMap(final String label) {
		// em.joinTransaction();
		final TypedQuery<SiteMapEntryDO> createQuery = em.createQuery("from SiteMapEntryDO where label = :label", SiteMapEntryDO.class);
		createQuery.setParameter("label", label);

		final SiteMapEntryDO singleResult;
		try {
			singleResult = createQuery.getSingleResult();
		} catch (final Exception e) {
			return null;
		}
		return singleResult;
	}
}
